const globaldata = getApp().globalData.domain
Page({
  data: {
    organizations: [], //排序后的部门信息
    swiperImg: [],
    swiperCurrent: 1,
    sortItem: [{
        id: 0,
        title: '热门指数',
        topImage: '/image/origin.png',
        bottomImage: '/image/origin.png',
        name: 'deliverNum',
        status: null
      },
      {
        id: 1,
        title: '招新人数',
        topImage: '/image/origin.png',
        bottomImage: '/image/origin.png',
        name: 'recruitNum',
        status: null
      },
      {
        id: 2,
        title: '发布时间',
        topImage: '/image/origin.png',
        bottomImage: '/image/origin.png',
        name: 'startTime',
        status: null
      },
    ], //排序内容
    tips: "在招列表加载中...", //无部门信息时出现的提示
    isSearching: false, //是否点开搜索
    searchOrgan: [] //搜索结果
  },
  onShow() {
    //更新选中的tarbar下标并且更新，不可删否则bug
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selectIndex: 0
      })
    }
  },

  async onLoad() {
    const that = this
    try {
      //获取活动信息
      var activityInfo = await getApp().getActivityInfo()
      //获取部门logo
      activityInfo.forEach(async (item, index) => {
        //获取部门信息
        const deptInfo = await getApp().getDeptInfo(item.deptId)
        //设置logo地址
        item.logo = deptInfo.logo
      })
      //更新活动信息
      this.setData({
        organizations: activityInfo,
        tips: ''
      })
      //模拟点击热门指数按钮以加载logo
      setTimeout(() => {
        this.changeSelect({
          currentTarget: {
            dataset: {
              index: 0
            }
          }
        })
      }, 500)
    } catch (error) {
      console.log(error)
      switch (error) {
        case 'token非法':
          that.changeTips("token非法！请尝试重启小程序！")
        case 'other':
          that.changeTips("在招列表加载失败！")
        case 'ERR_CONNECTION_RESET':
          that.changeTips("网络异常，请检查网络连接")
      }
    }
    //获取海报
    await that.getSwiper(1)
  },
  //选择筛选顺序
  changeSelect(e) {
    //显示加载中
    getApp().showLoading('加载中');
    //获取活动列表
    const activityArray = this.data.organizations
    console.log('活动列表', activityArray)
    //获取目前选择清况
    var sortItem = this.data.sortItem
    //获取排序内容
    const sortIndex = e.currentTarget.dataset.index
    var currentSort = sortItem[sortIndex].name;
    //加载图片
    const origin = '/image/origin.png';
    const selected = '/image/select.png'
    //根据选择情况更改显示内容
    var completeArray;
    sortItem.forEach((item, index) => {
      if (index != sortIndex) return;
      if (!item.status) { //状态为空或假，则改为真（顺序排序）
        item.topImage = selected
        item.bottomImage = origin
        item.status = true
        completeArray = this.sortArray(activityArray, currentSort, item.status)
      } else if (item.status) { //状态为真，则改为假
        item.topImage = origin
        item.bottomImage = selected
        item.status = false
        completeArray = this.sortArray(activityArray, currentSort, item.status)
      }
    })
    //渲染排序结果
    this.setData({
      organizations: completeArray,
      sortItem: sortItem
    })
    //关闭模态框
    wx.hideToast();
  },
  //跳转到组织介绍
  navToIntroduce(e) {
    const id = e.currentTarget.dataset.index
    const url = '/pages/introduce/introduce'
    const data = getApp().queryStringify({
      deptId: id
    })
    wx.navigateTo({
      url: `${url}?${data}`,
      fail: function (err) {
        console.error(err)
        getApp().showMessage("跳转失败！")
      }
    })
  },
  //数组排序
  sortArray(arr, propertyName, ascending = true) {
    // 创建一个新数组以避免修改原数组  
    let newArr = [...arr];
    // 使用sort方法和一个自定义的比较函数来排序  
    newArr.sort((a, b) => {
      // 确保a和b都有propertyName属性  
      if (!a.hasOwnProperty(propertyName) || !b.hasOwnProperty(propertyName)) {
        throw new Error('All objects in the array must have the specified property.');
      }
      // 根据propertyName属性进行比较  
      let valueA = a[propertyName];
      let valueB = b[propertyName];
      // 根据值的类型进行不同的比较  
      if (typeof valueA === 'string' || typeof valueB === 'string') {
        // 如果属性值是字符串，则使用localeCompare进行比较  
        return ascending ? valueA.localeCompare(valueB) : valueB.localeCompare(valueA);
      } else {
        // 如果属性值是数字，则直接进行数值比较  
        return ascending ? valueA - valueB : valueB - valueA;
      }
    });

    return newArr;
  },
  //控制无部门信息时的提示内容
  changeTips(msg) {
    this.setData({
      tips: msg
    })
  },
  //显示搜索面板
  startSearch() {
    this.setData({
      isSearching: !this.data.isSearching,
      searchOrgan: []
    })
  },
  //输入搜索词
  search(e) {
    const searchInput = e.detail.value
    //无内容时清空搜索结果
    if (searchInput == '') {
      this.setData({
        searchOrgan: []
      })
      return
    }
    //获取目前的组织名称数组 
    const organArray = this.data.organizations
    var nameArray = []
    organArray.forEach((item, index) => {
      nameArray.push(item.title)
    })
    //开搜
    const indexArray = this.fuzzySearch(nameArray, searchInput)
    var resultArray = []
    indexArray.forEach((item, index) => {
      resultArray.push(organArray[item])
    })
    this.setData({
      searchOrgan: resultArray
    })
  },
  //模糊搜索
  fuzzySearch(array, query) {
    const regex = new RegExp(query.split('').map(char => `(${char})`).join('.*'), 'i');
    const indices = [];

    array.forEach((item, index) => {
      if (regex.test(item)) {
        indices.push(index);
      }
    });

    return indices;
  },
  //获取海报
  getSwiper(current) {
    const that = this
    return new Promise((resolve, reject) => {
      wx.request({
        url: globaldata + '/api/ad/list/page',
        method: 'POST',
        header: {
          'content-type': 'application/json',
          token: wx.getStorageSync('token')
        },
        data: {
          "current": current,
          "pageSize": 10,
        },
        success: async (res) => {
          console.log(res.data)
          const resData = res.data.data
          var resArray = resData.records
          //检测获取海报数量，如果为0则返回false
          if (resArray[0]) {
            //获取目前海报列表
            var nowArray = that.data.swiperImg
            //把新获取的海报塞入海报列表中
            resArray.forEach((item, index) => {
              //筛选url，只放入图片url
              if(that.isImage(item.url)){
                nowArray.push(item.url)
              }
            })
            //渲染处理后的数组
            that.setData({
              swiperImg: nowArray,
              swiperCurrent: that.data.swiperCurrent + 1
            })
            //递归函数
            await that.getSwiper(that.data.swiperCurrent)
          } else {
            resolve(false)
          }
        },
        fail: err => {
          console.error(err)
        }
      })
    })
  },
  //判断url是否为图片
  isImage(url) {
    const imageExtensions = /\.(jpeg|jpg|png|gif|bmp|webp)$/i;
    return imageExtensions.test(url);
  }
})